<template>
  <view class="time-slot-manager">
    <view class="header">
      <view class="headtab">
        <up-tabs :list="tabs" @click="handleTabClick" lineColor="rgba(214, 142, 68, 1)"
          itemStyle="flex:1; height: 48px;" :activeStyle="{ color: 'rgba(214, 142, 68, 1)' }"></up-tabs>
      </view>
      <view class="cutomer-data" v-if="currentTab == 0">
        <view class="date">{{ currentDate }}</view>
        <view>合计:客流量 <text>{{ totalCustomNum }}</text> 试穿人数 <text>{{ totalTryWear }}</text></view>
      </view>
    </view>

    <scroll-view scroll-y class="time-slots">
      <view v-if="currentTab == 0">
        <view class="time-slot" v-for="(slot, index) in shopDataDetails" :key="index">
          <view class="time-range">时段：<text class="time">{{ slot.startTime }}-{{ slot.endTime }}</text></view>
          <view class="metrics">
            <view class="metric-item">
              <text class="label">客流量</text>
              <up-input type="number" v-model="slot.customNum" inputAlign="right" :border="'none'" class="input"
                placeholder="请输入客流量" />
            </view>
            <view class="metric-item">
              <text class="label">试穿人数</text>
              <up-input type="number" inputAlign="right" :border="'none'" v-model="slot.tryWear" class="input"
                placeholder="请输入试穿人数" />
            </view>
          </view>
        </view>
      </view>
      <view v-else>
        <view class="user-list flex items-center justify-between" @click="showOpenDate = true">
          <text class="list-name">日期</text>
          <view class="flex items-center">
            <text class="list-val">{{ openDate ? openDate : "请选择日期~" }}</text>
            <image class="chevronright" :src="IMG_URL2 + 'common/chevron-right.svg'"></image>
          </view>
        </view>
        <view class="time-slot" v-for="(slot, index) in HistoryshopData" :key="index" @click="goToDetails(slot, 1)">
          <view class="time-range1">{{ slot.createTime }}</view>
          <view class="metrics1">
            <view class="metric-item">
              <text class="label">客流量</text>
              <text class="value">{{ slot.totalCustomNum || '请填写' }}</text>
            </view>
            <view class="metric-item">
              <text class="label">试穿人数</text>
              <text class="value">{{ slot.totalTryWear || '请填写' }}</text>
            </view>
          </view>
        </view>
        <up-divider v-if="HistoryshopData.length > pageSize" :text="loadStatus"></up-divider>
      </view>
    </scroll-view>
    <up-datetime-picker :show="showOpenDate" v-model="value1" mode="date" @cancel="cancelOpenDate"
      @confirm="confirmOpenDate"></up-datetime-picker>
    <view class="footer" v-if="currentTab == 0">
      <button class="save-btn" @click="handleSave" :disabled="loading">
        <up-loading-icon class="loading" color="#fff" size="16" :show="loading"></up-loading-icon><text>保存</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { IMG_URL2 } from "@/config";
import { shopApi, studyApi } from "@/api";
import {formatDate} from '@/utils/util';
const loading = ref(false);
let showOpenDate = ref(false);
let value1 = ref(Date.now());
const getCurrentTime = () => {
  const now = new Date();

  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`
}
const currentDate = ref(getCurrentTime())
const currentTab = ref(0)
const tabs = ref([
  { name: '当天数据' },
  { name: '历史数据' }
])

const openDate=ref('')
const opentime=ref('')

const totalCustomNum = computed(() => {
  return shopDataDetails.value.reduce((total, item) => total + Number(item.customNum || 0), 0);
});

const totalTryWear = computed(() => {
  return shopDataDetails.value.reduce((total, item) => total + Number(item.tryWear || 0), 0);
});

const shopDataDetails = ref([
  {
    startTime: '8:00',
    endTime: '10:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '10:00',
    endTime: '12:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '12:00',
    endTime: '14:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '14:00',
    endTime: '16:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '16:00',
    endTime: '18:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '18:00',
    endTime: '20:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '20:00',
    endTime: '22:00',
    customNum: '',
    tryWear: ''
  }
])
let CurrentshopDataDetailsData = ref([]);
const shopDataDetails1 = [
  {
    startTime: '8:00',
    endTime: '10:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '10:00',
    endTime: '12:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '12:00',
    endTime: '14:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '14:00',
    endTime: '16:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '16:00',
    endTime: '18:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '18:00',
    endTime: '20:00',
    customNum: '',
    tryWear: ''
  },
  {
    startTime: '20:00',
    endTime: '22:00',
    customNum: '',
    tryWear: ''
  }
]
let shopCountDataId=ref(null)
let HistoryshopData = ref([])
let currentPage = ref(1)
let pageSize = ref(15)
let totalCount = ref(0)
let loadStatus = ref('正在加载中')

const cancelOpenDate = () => {
  showOpenDate.value = false
}
const confirmOpenDate = (e) => {
  openDate.value = formatDate(e.value)
  
  opentime.value= formatDate(e.value)
  showOpenDate.value = false
  currentPage.value = 1
  getOutData(1)
}
const handleTabClick = (item) => {
  currentTab.value = item.index
  value1.value = Date.now()
  opentime.value=''
  openDate.value =''
  currentPage.value = 1
  if (item.index == 1) {
    
    loadStatus.value = '正在加载中'
    getOutData(1)
  } else {
    getCurrentData()
  }
}
const goToDetails = (item, type) => {
  uni.navigateTo({
    url: `/pagesshop/businessdata/details?time=${item.createTime}&shopCountDataId=${item.shopCountDataId}`
  });
};
const handleSave = () => {
  const newDatashopDataDetails = shopDataDetails.value.filter(item => {
    return item.customNum!== "" && item.tryWear!== "";
  });
  if(newDatashopDataDetails.length==0){
    uni.showToast({ title: '请填写客流量和试穿人数', icon: "none" });
    return
  }
  let params = {
    createTime: getCurrentTime(),
    totalCustomNum: totalCustomNum.value,
    totalTryWear: totalTryWear.value,
    shopDataDetails: newDatashopDataDetails,
    
  }
  if(shopCountDataId.value){
    params.shopCountDataId=shopCountDataId.value
  }
  loading.value = true;
  shopApi.SHOPSAVEORUPDATESHOPDATA(params).then((res) => {
    loading.value = false;
    if (res.code == 200) {
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      })
    } else {
      uni.showToast({ title: res.errMsg, icon: "none" });
    }
  })
}
const getCurrentData = () => {
  shopApi.SHOPGETSHOPDATABYTIME({ createTime: getCurrentTime() }).then((res) => {
    if (res.code == 200) {
      shopCountDataId.value=res.result.shopCountDataId
      // shopDataDetails.value = res.result ? res.result.shopDataDetails : shopDataDetails1
      CurrentshopDataDetailsData.value = res.result.shopDataDetails;
      CurrentshopDataDetailsData.value.forEach(historyItem => {
        shopDataDetails.value.forEach(slot => {
          if (slot.startTime === historyItem.startTime && slot.endTime === historyItem.endTime) {
            slot.customNum = historyItem.customNum;
            slot.tryWear = historyItem.tryWear;
          }
        });
      });
    } else {
      uni.showToast({ title: res.errMsg, icon: "none" });
    }

  })
}

const getOutData = (type) => {
  let params = {
    currentPage: 1,
    pageSize: 15,
    time: opentime.value
  }
  shopApi.SHOPGETSHOPDATA(params).then((res) => {
    if (res.code == 200) {
      if (type == 1) {
        HistoryshopData.value = res.result.data
        totalCount.value = res.result.totalCount
      } else {
        HistoryshopData.value = HistoryshopData.value.concat(res.result.data)
      }
    } else {
      uni.showToast({ title: res.errMsg, icon: "none" });
    }

  })
}
onReachBottom(() => {
  console.log("触底加载");
  if (currentTab.value == 0) {

  } else {
    if (HistoryshopData.value.length >= totalCount.value) {
      loadStatus.value = "没有更多数据了";
      return
    }
    loadStatus.value = "正在加载中";
    currentPage.value++
    getOutData(2)
  }

});

// 下拉刷新
onPullDownRefresh(() => {
  uni.showToast({
    title: "下拉刷新",
    icon: "none",
    duration: 1000
  });
  loadStatus.value = "正在加载中";
  if (currentTab.value == 0) {

  } else {
    currentPage.value = 1
    totalCount.value = 0
    isloading.value = false
    HistoryshopData.value = [];
    getOutData(1)
  }

  setTimeout(() => {
    uni.stopPullDownRefresh();
  }, 2000);
});
onLoad(async () => {
  getCurrentData()
})
</script>

<style lang="scss" scoped>
.time-slot-manager {
  width: 100%;
  height: 100vh;
  overflow: scroll;
  background-color: #f5f5f5;

  .header {
    width: 100%;
    box-sizing: border-box;
    position: sticky;
    top: 0;
    z-index: 100;

    .headtab {
      width: 100%;
      background: #fff;
      padding: 24rpx 24rpx 0 24rpx;
      box-sizing: border-box;
      border-bottom: 24rpx solid #f5f5f5;
    }

    .cutomer-data {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: #f5f5f5;
      padding: 0rpx 24rpx 24rpx 24rpx;
      box-sizing: border-box;
      font-size: 14px;
      font-weight: 400;
      line-height: 22px;
      color: rgba(0, 0, 0, 0.6);

      .date {
        font-size: 28rpx;
        color: rgba(0, 0, 0, 0.6);
      }
    }
  }

  .user-list {
    background: #fff;
    height: 100rpx;
    border-bottom: 1rpx solid #f6f6f6;
    padding: 0 20rpx;
    box-sizing: border-box;
    margin-bottom: 24rpx;
    .chevronright {
      width: 32rpx;
      height: 32rpx;
      margin-left: 24rpx;
    }

    .list-name {
      font-size: 32rpx;
      color: rgba(0, 0, 0, 0.6);
    }

    .list-val {
      color: #999;
      font-size: 28rpx;
      text-align: right;
    }
  }

  .time-slots {
    flex: 1;
    padding: 0 0 124rpx 0;
    box-sizing: border-box;
    margin-bottom: 100rpx;

    .time-slot {
      background-color: #fff;
      border-radius: 12rpx;
      padding: 24rpx;
      box-sizing: border-box;
      margin-bottom: 24rpx;

      .time-range {
        font-size: 32rpx;
        color: rgba(0, 0, 0, 0.6);
        margin-bottom: 24rpx;

        .time {
          color: rgba(214, 142, 68, 1);
        }
      }

      .time-range1 {
        //styleName: Title/Small;
        font-family: PingFang SC;
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
        text-align: left;
        text-underline-position: from-font;
        text-decoration-skip-ink: none;
        color: rgba(0, 0, 0, 0.6);
      }

      .metrics {
        display: flex;
        flex-direction: column;
        gap: 20rpx;

        .metric-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          height: 72rpx;

          .label {
            font-size: 28rpx;
            color: #666;
          }

          .value {
            font-size: 28rpx;
            color: #333;
          }
        }
      }

      .metrics1 {
        display: flex;
        justify-content: space-between;

        .metric-item {
          flex: 1;
          display: flex;
          align-items: center;
          height: 72rpx;

          .label {
            font-size: 28rpx;
            color: #666;
          }

          .value {
            font-size: 28rpx;
            color: #333;
            margin-left: 8rpx;
          }
        }
      }
    }
  }

  .footer {
    padding: 20rpx;
    box-sizing: border-box;
    background-color: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 99;
    .save-btn {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      background-color: #c4996c;
      color: #fff;
      border: none;
      border-radius: 40rpx;
      font-size: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      &:active {
        opacity: 0.9;
      }
    }
  }
}
</style>